package edu.biwu.cookie03;/**
 * @author 王俊彪
 * @version 1.0
 */

import edu.biwu.utils.CookieUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/lastVisited")
public class LastVisited extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        response.setContentType("text/html;charset=utf-8");
        Cookie cookie = CookieUtils.getCookie(cookies, "lastVisited");//得到这个cookie
        if(cookie==null){
            //说明是第一次访问
            response.getWriter().write("欢迎第一次访问");
        }else{
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("您上次访问的时间是："+cookie.getValue());
        }
        String format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        Cookie lastVisitedCookie = new Cookie("lastVisited", format);
        lastVisitedCookie.setMaxAge(7*24*60*60);//设置最大存活时间为7天
        lastVisitedCookie.setPath(request.getContextPath());
        response.addCookie(lastVisitedCookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
